/***** BEGIN LICENSE BLOCK *****
 Version: MPL 1.1
 
 The contents of this file are subject to the Mozilla Public License Version 
 1.1 (the "License"); you may not use this file except in compliance with 
 the License. You may obtain a copy of the License at 
 http://www.mozilla.org/MPL/
 
 Software distributed under the License is distributed on an "AS IS" basis,
 WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 for the specific language governing rights and limitations under the
 License.
 
 The Original Code is GureGipuzkoa Extension.
 
 The Initial Developer of the Original Code is Julen Ruiz Aizpuru.
 Portions created by the Initial Developer are Copyright (C) 2009
 the Initial Developer. All Rights Reserved.
 
 Contributor(s):
    Asier Sarasua Garmendia <asier.sarasua@gmail.com>
    Julen Ruiz Aizpuru <julenx@gmail.com>
    Juanan Pereira <juanan@diariolinux.com>
 
 ***** END LICENSE BLOCK *****/


const ggUpload = {
  files: new Array(),

  onAdd:
    function() {
      var filename = document.getElementById("gg-up-filename");
      var title_es = document.getElementById("gg-up-ptitle-es");
      var title_eu = document.getElementById("gg-up-ptitle-eu");
      var tags = document.getElementById("gg-up-tags");
      var description_es = document.getElementById("gg-up-description-es");
      var description_eu = document.getElementById("gg-up-description-eu");
//      var lang = document.getElementById("gg-up-lang");
      var license = document.getElementById("gg-up-license");
      var author = document.getElementById("gg-up-photographer");
      var lat = document.getElementById("gg-up-latitude");
      var lon = document.getElementById("gg-up-longitude");
      var album = document.getElementById("gg-up-album");
      var pdate = document.getElementById("gg-up-date");
      var img = document.getElementById("gg-up-thumbnail");

      // Upload check logic
      // TODO: add check logic for the album dropdown box
      if (filename.value == "") {
        gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                               gureGipuzkoaStrUtils.strBundle.getString("FilenameMissing"));
        return false;
      }
      if (license.selectedItem.value == 0) {
        gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                               gureGipuzkoaStrUtils.strBundle.getString("LicenseMissing"));
        return false;
      }
      if ((title_es.value == "") && (description_es.value == "") && 
          (title_eu.value == "") && (description_eu.value == "")) {
        gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                               gureGipuzkoaStrUtils.strBundle.getString("TitleDescMissing"));
        return false;
      }

      // Check for conflictive files, otherwise store and add
      for (var i = 0; i < this.files.length; i++) {
        if (this.files[i].name == filename.value) {
          gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                                 gureGipuzkoaStrUtils.strBundle.getFormattedString("FileExists", [filename.value]));
          return false;
        }
      }

      this.files.push({src: img.src,
                       name: filename.value,
                       title_eu: gureGipuzkoaStrUtils.removeTags(title_eu.value),
                       title_es: gureGipuzkoaStrUtils.removeTags(title_es.value),
                       tags: tags.value,
                       desc_eu: gureGipuzkoaStrUtils.removeTags(description_eu.value),
                       desc_es: gureGipuzkoaStrUtils.removeTags(description_es.value),
//                       lang: lang.selectedItem.value,
                       license: license.selectedItem.value,
                       author: author.value,
                       lat: lat.value,
                       lon: lon.value,
                       album: album.selectedItem.value,
                       pdate: pdate.value,
                       state: gureGipuzkoaStrUtils.strBundle.getString("UStatusPending")});

      // Add current values to the tree
      var treeChildren = document.getElementById("gg-up-tree-children");
      var it = document.createElement("treeitem");
      treeChildren.appendChild(it);
      var rw = document.createElement("treerow");
      it.appendChild(rw);
      var cl1 = document.createElement("treecell");
      var cl3 = document.createElement("treecell");
      rw.appendChild(cl1);
      rw.appendChild(cl3);
      cl1.setAttribute("label", filename.value);
      cl3.setAttribute("label", gureGipuzkoaStrUtils.strBundle.getString("UStatusPending"));

      this.clearValues();
      this.checkUploadButton();
      gureGipuzkoaUIUtils.disableEXIF();
    },

  reBuildTree:
    function() {
      var treeChildren = document.getElementById("gg-up-tree-children");
      for (var i = 0; i < this.files.length; i++) {
        var it = document.createElement("treeitem");
        treeChildren.appendChild(it);
        var rw = document.createElement("treerow");
        it.appendChild(rw);
        var cl1 = document.createElement("treecell");
        var cl3 = document.createElement("treecell");
        rw.appendChild(cl1);
        rw.appendChild(cl3);
        cl1.setAttribute("label", this.files[i].name);
        cl3.setAttribute("label", this.files[i].state);
      }
    },

  onSelect:
    function() {
      var tree = document.getElementById("gg-upload-list");
      var treeChildren = document.getElementById("gg-up-tree-children");

      var start = new Object();
      var end = new Object();
      var numRanges = tree.view.selection.getRangeCount();

      // Display information for the element clicked first
      if (numRanges == 0) {
        this.clearValues();
        gureGipuzkoaUIUtils.disableEXIF();
      } else {
        var filename = document.getElementById("gg-up-filename");
        var title_eu = document.getElementById("gg-up-ptitle-eu");
        var title_es = document.getElementById("gg-up-ptitle-es");
        var tags = document.getElementById("gg-up-tags");
        var description_eu = document.getElementById("gg-up-description-eu");
        var description_es = document.getElementById("gg-up-description-es");
        // var lang = document.getElementById("gg-up-lang");
        var license = document.getElementById("gg-up-license");
        var author = document.getElementById("gg-up-photographer");
        var lat = document.getElementById("gg-up-latitude");
        var lon = document.getElementById("gg-up-longitude");
        var album = document.getElementById("gg-up-album");
        var pdate = document.getElementById("gg-up-date");

        tree.view.selection.getRangeAt(0, start, end);
        var selectedFN = tree.view.getItemAtIndex(start.value)
                                  .getElementsByTagName("treecell")[0]
                                  .getAttribute("label");
          for (var j = 0; j < this.files.length; j++) {
            if (this.files[j].name == selectedFN) {
              filename.value = this.files[j].name;
              title_eu.value = this.files[j].title_eu;
              title_es.value = this.files[j].title_es;
              tags.value = this.files[j].tags;
              description_eu.value = this.files[j].desc_eu;
              description_es.value = this.files[j].desc_es;
//              var selectedLang = lang.getElementsByAttribute("value", this.files[j].lang)[0];
//              lang.selectedIndex = lang.getIndexOfItem(selectedLang);
              license.selectedIndex =
                gureGipuzkoaUIUtils.getIndexByValue(license, this.files[j].license);
              author.value = this.files[j].author;
              lat.value = this.files[j].lat;
              lon.value = this.files[j].lon;
              album.selectedIndex =
                gureGipuzkoaUIUtils.getIndexByValue(album, this.files[j].album);
              pdate.value = this.files[j].pdate;
              var previewBox = document.getElementById("gg-up-file-preview");
              var image = document.createElement("image");
              image.setAttribute("id", "gg-up-thumbnail");
              image.setAttribute("src", this.files[j].src);
              image.setAttribute("onload", "ggPhotos.resizeImage('gg-up-thumbnail');");
              previewBox.removeChild(previewBox.firstChild);
              previewBox.appendChild(image);
              break;
            }
          }
          gureGipuzkoaUIUtils.enableEXIF();
      }

    },

  onRemove:
    function() {
      var tree = document.getElementById("gg-upload-list");
      var treeChildren = document.getElementById("gg-up-tree-children");
      var delarray = new Array();

      var start = new Object();
      var end = new Object();
      var numRanges = tree.view.selection.getRangeCount();

      for (var t = 0; t < numRanges; t++) {
        tree.view.selection.getRangeAt(t, start, end);
        for (var v = start.value; v <= end.value; v++) {
          delarray.push(tree.view.getItemAtIndex(v));
        }
      }

      // Remove selected treeitems as well as the corresponding entries in this.files
      for (var i = 0; i < delarray.length; i++) {
          var filename = delarray[i].getElementsByTagName("treecell")[0].getAttribute("label");
          for (var j = 0; j < this.files.length; j++) {
            if (this.files[j].name == filename) {
              this.files.splice(j, 1);
              break;
            }
          }
          treeChildren.removeChild(delarray[i]);
      }

      this.checkUploadButton();
    },

  onClear:
    function(preserveFiles) {
      var treeChildren = document.getElementById("gg-up-tree-children");
      while (treeChildren.firstChild) {
        treeChildren.removeChild(treeChildren.firstChild);
      }
      if (!preserveFiles)
        this.files = new Array();

      this.checkUploadButton();
      gureGipuzkoaUIUtils.disableEXIF();
    },

  clearValues:
    function() {
      var filename = document.getElementById("gg-up-filename");
      var title_eu = document.getElementById("gg-up-ptitle-eu");
      var title_es = document.getElementById("gg-up-ptitle-es");
      var tags = document.getElementById("gg-up-tags");
      var description_eu = document.getElementById("gg-up-description-eu");
      var description_es = document.getElementById("gg-up-description-es");
//      var lang = document.getElementById("gg-up-lang");
      var license = document.getElementById("gg-up-license");
      var author = document.getElementById("gg-up-photographer");
      var lat = document.getElementById("gg-up-latitude");
      var lon = document.getElementById("gg-up-longitude");
      var album = document.getElementById("gg-up-album");
      var pdate = document.getElementById("gg-up-date");

      filename.value = "";
      title_eu.value = "";
      title_es.value = "";
      tags.value = "";
      description_eu.value = "";
      description_es.value = "";
      author.value = "";
      lat.value = 0;
      lon.value = 0;
      album.selectedIndex = 0;
      pdate.dateValue = new Date();
      var defaultLang = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.lang.default");
      // lang.selectedIndex = gureGipuzkoaUIUtils.getIndexByValue(lang, defaultLang);
      var defaultLicense = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.license.default");
      license.selectedIndex = gureGipuzkoaUIUtils.getIndexByValue(license, defaultLicense);
      var previewBox = document.getElementById("gg-up-file-preview");
      var label = document.createElement("label");
      label.setAttribute("value", gureGipuzkoaStrUtils.strBundle.getString("UploadDrop"));
      previewBox.removeChild(previewBox.firstChild);
      previewBox.appendChild(label);
    },

  checkUploads:
    function() {
      if (this.files.length == 0)
        return true;
      for (var i = 0; i < this.files.length; i++) {
        if (this.files[i].state == gureGipuzkoaStrUtils.strBundle.getString("UStatusPending") ||
            this.files[i].state == gureGipuzkoaStrUtils.strBundle.getString("UStatusFailed"))
          return false;
      }
      return true;
    },

  checkUploadButton:
    function() {
      var upload = document.getElementById("gg-up-button");
      var login = ggAccounts.getLogin();
      upload.disabled = this.checkUploads() || !login;
    },

  checkUploadProgress:
    function(start) {
      var progress = document.getElementById("gg-up-progress");
      if (start) {
        progress.value = 0;
        progress.setAttribute("hidden", "false");
      } else {
        var count = this.getUploadCount();
        if (count == 0) {
          progress.setAttribute("hidden", "true");
        }
      }
    },

  getUploadCount:
    function() {
      var count = 0;
      for (var i in this.files) {
        if (this.files[i].state == gureGipuzkoaStrUtils.strBundle.getString("UStatusPending") ||
            this.files[i].state == gureGipuzkoaStrUtils.strBundle.getString("UStatusUploading")) {
          count++;
        }
      }
      return count;
    },

  onUpload:
    function() {
      /* Each time we press the upload button we will retrieve a new token
       * just in case it's out of date. The first token is always retrieved
       * on startup or when logging in.
       * Lifetime: 1 hour.
       */
      gureGipuzkoa.getToken();
      this.checkUploadProgress(true);
      for (var i in this.files) {
        var file = this.files[i];
        if (file.state == gureGipuzkoaStrUtils.strBundle.getString("UStatusPending") ||
            file.state == gureGipuzkoaStrUtils.strBundle.getString("UStatusFailed")) {
          ggUpload.files[i].state = gureGipuzkoaStrUtils.strBundle.getString("UStatusUploading");
          ggUpload.onClear(true);
          ggUpload.reBuildTree();
          gureGipuzkoa.uploadFile(file.name,
                                  gureGipuzkoaStrUtils.getUploadParams(file),
                                  function(i) {
                                    ggUpload.files[i].state =
                                      gureGipuzkoaStrUtils.strBundle.getString("UStatusComplete");
                                    ggUpload.onClear(true);
                                    ggUpload.reBuildTree();
                                    ggUpload.checkUploadButton();
                                    ggUpload.checkUploadProgress(false);
                                  },
                                  function(i) {
                                    ggUpload.files[i].state =
                                      gureGipuzkoaStrUtils.strBundle.getString("UStatusFailed");
                                    ggUpload.onClear(true);
                                    ggUpload.reBuildTree();
                                    ggUpload.checkUploadButton();
                                    ggUpload.checkUploadProgress(false);
                                  }, i);
        }
      }
    },

  getExifData:
    function() {
      var thumbnail = document.getElementById("gg-up-thumbnail");
      var imageURI = thumbnail.getAttribute("src");
      data = ggExifUtils.gatherData(imageURI);
      if (data != null) {
        var latBox = document.getElementById("gg-up-latitude");
        var lonBox = document.getElementById("gg-up-longitude");
        latBox.value = parseFloat(data.GPSPureDdLat);
        lonBox.value = parseFloat(data.GPSPureDdLon);
      }
    },

  appendFile:
    function(file) {
      this.clearValues();
      gureGipuzkoaUIUtils.enableEXIF();

      var fileName = document.getElementById("gg-up-filename");
      fileName.value = file.path;

      var previewBox = document.getElementById("gg-up-file-preview");
      var image = document.createElement("image");
      image.setAttribute("id", "gg-up-thumbnail");
      image.setAttribute("src", gureGipuzkoaStrUtils.getURIFromFile(file));
      image.setAttribute("onload", "ggPhotos.resizeImage('gg-up-thumbnail');");
      previewBox.removeChild(previewBox.firstChild);
      previewBox.appendChild(image);
    },

  appendURI:
    function(uri) {
      var ios = Components.classes["@mozilla.org/network/io-service;1"]
                          .getService(Components.interfaces.nsIIOService);
      var fileURI = ios.newURI(uri, null, null);
      var file = fileURI.QueryInterface(Components.interfaces.nsIFileURL).file;
      this.appendFile(file);
    },

  showFilePicker:
    function() {
      const nsIFilePicker = Components.interfaces.nsIFilePicker;
      var fPicker = Components.classes["@mozilla.org/filepicker;1"]
                              .createInstance(nsIFilePicker);
      fPicker.init(window, gureGipuzkoaStrUtils.strBundle.getString("UploadTitle"),
                           nsIFilePicker.modeOpen);
      var filterList = "*.png; *.PNG; *.gif; *.GIF; *.jpg; *.JPG; *.jpeg; *.JPEG; *.tiff; *.TIFF";
      fPicker.appendFilter(gureGipuzkoaStrUtils.strBundle.getString("FilterImg"), filterList);
      fPicker.appendFilter(gureGipuzkoaStrUtils.strBundle.getString("FilterAll"), "*.*");

      if (fPicker.show() == nsIFilePicker.returnOK) {
        var file = fPicker.file.QueryInterface(Components.interfaces.nsIFile);
        this.appendFile(file);
      }
    },

  imgObserver: {

    getSupportedFlavours:
      function() {
        var flavours = new FlavourSet();
        flavours.appendFlavour("application/x-moz-file", "nsIFile");
        flavours.appendFlavour("application/x-moz-url");
        flavours.appendFlavour("text/uri-list");
        flavours.appendFlavour("text/unicode");
        return flavours;
      },

    onDragOver:
      function(event, flavour) {
        previewBox = document.getElementById("gg-up-file-preview");
        previewBox.setAttribute('class', 'dragover');
      },

    onDragExit:
      function(event) {
        previewBox = document.getElementById("gg-up-file-preview");
        previewBox.setAttribute('class', '');
      },

    onDrop:
      function(event, transferData) {
        previewBox = document.getElementById("gg-up-file-preview");
        previewBox.setAttribute('class', '');
        switch (transferData.flavour.contentType) {
          case 'application/x-moz-file':
            ggUpload.appendFile(transferData.data);
          break;
          case 'text/uri-list':
            ggUpload.appendURI(gureGipuzkoaStrUtils.splitASCII(transferData.data));
            break;
          default:
            gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                                   transferData.flavour.contentType + 
                                   ':' + transferData.data);
            break;
        }
      }

  }

}

